package com.ita.httpclient;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.ita.dao.MerchantDao;
import com.ita.dao.impl.MerchantDaoImpl;
import com.ita.pojo.Merchant;
import com.ita.redis.MerchantBlockFactory;
import com.ita.service.MerchantService;
import com.ita.service.impl.MerchantServiceImpl;
import com.ita.util.Constant;
import com.ita.util.JsonUtil;
import com.ita.util.PropertiesUtil;
import com.ita.util.State;

public class CheckClient {

	private final static String GET_VERIFY_PATH = "GET_VERIFY_PATH";
	private static Logger logger=Logger.getLogger(CheckClient.class);
	private URL url;
	private HttpURLConnection hcon;
	private Properties prop;
	private MerchantDao md;

	public CheckClient(String id) throws IOException {
		prop = PropertiesUtil.getProp();
		url = new URL(prop.getProperty(GET_VERIFY_PATH) + id);
		md=new MerchantDaoImpl();
	}

	public State getState() throws IOException {
		try {
			
			hcon = (HttpURLConnection) url.openConnection();
			// hcon.setDoInput(true);
			// hcon.setDoOutput(true);
			hcon.setRequestMethod("GET");
			// hcon.setRequestProperty("header-key", "xxx");
			InputStream in = hcon.getInputStream();
			byte[] buf = new byte[in.available()];
			in.read(buf);
			Merchant merchant = JsonUtil.getObjectFromJson(new String(buf),
					Merchant.class);
			md.updateMer(merchant);
			MerchantBlockFactory.updateMerchant(merchant.getId(), merchant);
			in.close();
			hcon.disconnect();
			int state = merchant.getState();
			int block = merchant.getBlock();
			Constant.REASON=merchant.getMsg();
			if (block == Constant.BLOCK) {
				return State.BLOCK;
			}
			if (state == Constant.FAIL) {
				return State.FAIL;
			} else if (state == Constant.SUCCESS) {
				return State.PASS;
			}
			return State.DEFAULT;
		} catch (Exception e) {
			logger.error("remote Admin side has something error");
		}
		return State.ERROR;
	}

}
